package socket;

import org.junit.Test;

import java.lang.ref.*;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: feiwang_6
 * @create: 2020/9/20 11:59
 * @description:
 */
public class ObjectReferenceDemo {
    private Object object = new Object();
    private String str = "1231321";
    
    @Test
    public void softReference() throws InterruptedException {
        ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>();
        Map<Integer, SoftReference> map = new HashMap<>();
        for(int i = 0;i < 100;i++) {
            byte[] bytes = new byte[1024*1024*1024];
            SoftReference<byte[]> softReference = new SoftReference<byte[]>(bytes, referenceQueue);
            map.put(i, softReference);
        }
        System.out.println("map-size: " + map.size());
        int cnt = 0;
        SoftReference<byte[]> k;
        //当内存不足时，bytes数组会被回收一部分
        while((k = (SoftReference) referenceQueue.poll()) != null) {
            System.out.println((cnt++) + "bytes数组被回收了:" + k.get());
        }
        System.out.println("==========================================");
        System.out.println(map.size());
        map.entrySet().stream().forEach(f -> System.out.println(f.getKey() +" " + f.getValue().get()));
    }
    
    @Test
    public void weakReference() throws InterruptedException {
        ReferenceQueue<String> referenceQueue = new ReferenceQueue();
        WeakReference<String> weakReference = new WeakReference<>(new String("1234"), referenceQueue);
        System.out.println(weakReference.get());
        System.gc();
        Thread.sleep(500);
        System.out.println(weakReference.get());
        Reference<? extends String> reference = referenceQueue.poll();
        System.out.println("弱引用对象：" + reference);
        System.out.println("弱引用对象引用的对象：" + reference.get());
    }
    
    @Test
    public void phantomReference(){
        ReferenceQueue<String> referenceQueue = new ReferenceQueue();
        PhantomReference<String> phantomReference = new PhantomReference<>(new String("1234"), referenceQueue);
        //null
        System.out.println(phantomReference.get());

        WeakHashMap<Integer, Integer> map = new WeakHashMap<>();
        map.put(100, 1);
        
        ThreadLocal<Object> local = new ThreadLocal<>();
        local.set(new Object());

        ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        service.prestartAllCoreThreads();
        
        
        service.submit(new Thread());
    }
}
